import { ref } from "vue";
import { Md5 } from "ts-md5";

// 普通post请求参数加密转化
export function usePost(data: object) {
  const md5: any = new Md5();
  md5.appendAsciiStr(JSON.stringify(objKeySort({})));
  const sign = ref("");
  sign.value = md5.end();

  const params = ref({ sign, data });
  return params.value;
}

// 分页post请求参数加密转化
export function usePostPage(data: object, pageInfo: PageQuery) {
  const md5: any = new Md5();
  md5.appendAsciiStr(JSON.stringify(objKeySort({})));
  const sign = ref("");
  sign.value = md5.end();

  const params = ref({
    current: pageInfo.currentPage,
    size: pageInfo.pageSize,
    sort: pageInfo.sort,
    sign,
    data,
  });
  return params.value;
}

// GET请求
export function useGet(data: object) {
  const params = ref({
    data,
  });
  return params.value;
}

function objKeySort(obj: any) {
  //排序的函数
  const newkey = Object.keys(obj).sort();
  //先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
  const newObj: any = {}; //创建一个新的对象，用于存放排好序的键值对
  for (let i = 0; i < newkey.length; i++) {
    //遍历newkey数组
    newObj[newkey[i]] = obj[newkey[i]]; //向新创建的对象中按照排好的顺序依次增加键值对
  }
  return newObj; //返回排好序的新对象
}

// 回显字典label
export function useDictLabelShow(list: any, value: string | number) {
  const current = toRaw(list)?.filter((item: any) => item.value == value);
  return current[0]?.label || "";
}

export function filterOrder(order: string) {
  const newOrder =
    order === "descending" ? "desc" : order === "ascending" ? "asc" : "";

  return newOrder;
}

// 自定义表单下拉数据回显方法
export function handleSelectData(
  type: string,
  list: any,
  createFormConfig: any
) {
  let typeIndex = 0;
  createFormConfig.map((item: any, index: number) => {
    if (item.fieldName === type) {
      typeIndex = index;
    }
  });
  createFormConfig[typeIndex].optionList = list;
}

// 获取当前时间，number为空是当前时间，number为向前推几分钟
export function getNowTime(num?: number) {
  // 创建一个 Date 对象
  const today = new Date();
  if (num) {
    today.setMinutes(today.getMinutes() + num);
  } // 获取年、月、日、时、分、秒

  const year = today.getFullYear();
  const month = today.getMonth() + 1; // 月份是从 0 开始计数的，需要加1
  const day = today.getDate();
  const hours = today.getHours();
  const minutes = today.getMinutes();
  const seconds = today.getSeconds(); // 格式化输出

  const formattedTime =
    year +
    "-" +
    (month < 10 ? "0" : "") +
    month +
    "-" +
    (day < 10 ? "0" : "") +
    day +
    " " +
    (hours < 10 ? "0" : "") +
    hours +
    ":" +
    (minutes < 10 ? "0" : "") +
    minutes +
    ":" +
    (seconds < 10 ? "0" : "") +
    seconds;

  return formattedTime;
}

// type为2，则取整数
export function convertToChineseNumber(num: number, type = 1) {
  const chineseNumbers = [
    "零",
    "一",
    "二",
    "三",
    "四",
    "五",
    "六",
    "七",
    "八",
    "九",
  ];

  // 判断输入参数类型是否为数字
  if (typeof num !== "number" || isNaN(num)) {
    return "";
  }

  let result = "";
  let integerPart = Math.floor(Math.abs(num)); // 取绝对值并向下取整得到整数部分
  const decimalPart = Math.round((Math.abs(num) - integerPart) * 10); // 获取小数部分（保留两位）

  // 处理整数部分
  while (integerPart > 0) {
    const digit = integerPart % 10; // 取最低位数字
    result = chineseNumbers[digit] + result; // 添加当前数字到结果字符串开头

    integerPart = Math.floor(integerPart / 10); // 去除已经处理过的最低位数字
  }

  // 处理小数部分
  if (decimalPart === 0 && type === 1) {
    result += "整";
  } else if (decimalPart === 0 && type === 2) {
    result += "";
  } else {
    result += "点" + chineseNumbers[decimalPart];
  }

  // 根据正负号返回相应的结果
  if (num < 0) {
    result = "负" + result;
  }

  return result;
}

export function validateDegree(
  rule: any,
  value: any,
  callback: (a?: any) => {}
) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入数字"));
  } else if (!/^[+-]?\d*(\.\d*)?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入数字"));
  } else if (Number(value) > 100 || Number(value) < 0) {
    callback(new Error("完成度在0-100之间"));
  } else if (value.indexOf(".") !== -1) {
    callback(new Error("不能为小数"));
  } else {
    callback();
  }
}

export function validatePositiveInteger(
  rule: any,
  value: any,
  callback: (a?: any) => {}
) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入数字"));
  } else if (!/^[+-]?\d*(\.\d*)?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入数字"));
  } else if (value.indexOf(".") !== -1) {
    callback(new Error("不能为小数"));
  } else if (Number(value) <= 0) {
    callback(new Error("数字不能小于0"));
  } else {
    callback();
  }
}

export function validateNumber(
  rule: any,
  value: any,
  callback: (a?: any) => {}
) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入数字"));
  } else if (!/^[+-]?\d*(\.\d*)?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入数字"));
  } else if (Number(value) <= 0) {
    callback(new Error("请输入大于0的值"));
  } else {
    callback();
  }
}

export function validateZeroNumber(
  rule: any,
  value: any,
  callback: (a?: any) => {}
) {
  if (value) {
    if (isNaN(parseFloat(value)) && isFinite(value)) {
      callback(new Error("请输入数字"));
    } else if (!/^[+-]?\d*(\.\d*)?(e[+-]?\d+)?$/.test(value)) {
      callback(new Error("请输入数字"));
    } else if (Number(value) < 0) {
      callback(new Error("数字不能小于0"));
    } else {
      callback();
    }
  } else {
    callback();
  }
}

// 判断2024-04到2024-04中间间隔月份
export function getMonthDifference(startDate: string, endDate: string) {
  const start = new Date(startDate);
  const end = new Date(endDate);
  let yearsDifference = end.getFullYear() - start.getFullYear();
  let monthsDifference = end.getMonth() - start.getMonth();

  if (monthsDifference < 0) {
    monthsDifference += 12;
    yearsDifference--;
  }

  return yearsDifference * 12 + monthsDifference;
}

function chunkArray(array: any[], item?: "12") {
  const result: any = [];
  let elderIndex = 0; // 上一个索引
  let isYears = false; // 是否跨年

  const lastIndex = array.findLastIndex((e) => e === item);
  isYears = lastIndex === -1 ? false : true;
  if (isYears) {
    array.map((self: string, selfIndex: number) => {
      if (self === item) {
        result.push(array.slice(elderIndex, selfIndex + 1));
        elderIndex = selfIndex + 1;
        if (selfIndex === lastIndex) {
          result.push(array.slice(elderIndex, array.length));
        }
      }
    });
  } else {
    result.push(array);
  }

  return result;
}

export function getMonthsBetween(startDateStr: string, endDateStr: string) {
  let startDate = new Date(startDateStr);
  let endDate = new Date(endDateStr);

  const months = [];

  // 如果开始日期大于结束日期，则交换它们
  if (startDate > endDate) {
    [startDate, endDate] = [endDate, startDate];
  }

  const currentDate = new Date(startDate);
  currentDate.setDate(1); // 将日期设置为当月的第一天

  while (currentDate <= endDate) {
    months.push(currentDate.toISOString().split("-")[1]); // 提取月份并添加到数组中
    currentDate.setMonth(currentDate.getMonth() + 1); // 移动到下个月
  }

  return chunkArray(months, "12");
}

// 判断2024-04到2024-04中间间隔年份
export function getYearArray(startDate: string, endDate: string) {
  const start = new Date(startDate);
  const end = new Date(endDate);
  const startYears = start.getFullYear();
  const endYears = end.getFullYear();
  const arr = [];
  if (endYears === startYears) {
    arr.push(endYears);
  } else {
    const yearNumber = endYears - startYears;
    for (let i = 0; i <= yearNumber; i++) {
      arr.push(startYears + i);
    }
  }
  return arr;
}

export function validateIsNumber(
  rule: any,
  value: any,
  callback: (a?: any) => {}
) {
  if (isNaN(parseFloat(value)) && isFinite(value) && value) {
    callback(new Error("请输入数字"));
  } else if (!/^[+-]?\d*(\.\d*)?(e[+-]?\d+)?$/.test(value) && value) {
    callback(new Error("请输入数字"));
  } else {
    callback();
  }
}

//使用递归的方式实现数组、对象的深拷贝
export function deepClone(obj: any) {
  const objClone: any = Array.isArray(obj) ? [] : {};
  if (obj && typeof obj === "object") {
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        //判断ojb子元素是否为对象，如果是，递归复制
        if (obj[key] && typeof obj[key] === "object") {
          objClone[key] = deepClone(obj[key]);
        } else {
          //如果不是，简单复制
          objClone[key] = obj[key];
        }
      }
    }
  }
  return objClone;
}

/**
 * @description:  validateNumber 只能输入大于零的数字，可以为空
 * @returns {String}
 */
export function validateNumberCanNull(
  rule: any,
  value: any,
  callback: (a?: any) => {}
) {
  if (!value) {
    callback();
  } else if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入数字"));
  } else if (!/^[+-]?\d*(\.\d*)?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入数字"));
  } else if (Number(value) <= 0) {
    callback(new Error("请输入大于0的值"));
  } else {
    callback();
  }
}

// 可以不填写，但如果填写的话，必须是数字
export function validateNumberCanNot(
  rule: any,
  value: any,
  callback: (a?: any) => {}
) {
  if (value === "") {
    callback();
  } else {
    if (isNaN(parseFloat(value)) && isFinite(value)) {
      callback(new Error("请输入数字"));
    } else if (!/^[+-]?\d*(\.\d*)?(e[+-]?\d+)?$/.test(value)) {
      callback(new Error("请输入数字"));
    } else if (Number(value) <= 0) {
      callback(new Error("数字不能小于0"));
    } else {
      callback();
    }
  }
}

/**
 * @description:  validateNumber 只能输入大于零的数字
 * @returns {String}
 */
export function promptValidateNumber(value: any) {
  if (!value) {
    return "请输入数字";
  } else if (isNaN(parseFloat(value)) && isFinite(value)) {
    return "请输入数字";
  } else if (!/^[+-]?\d*(\.\d*)?(e[+-]?\d+)?$/.test(value)) {
    return "请输入数字";
  } else if (Number(value) <= 0) {
    return "请输入大于0的值";
  } else {
    return true;
  }
}
// 颜色变更处理(范围值是否出现异常)
export function sizeColorHandle(number: any, minNumber: any, maxNumber: any) {
  if (!minNumber && !maxNumber) {
    return "";
  }
  if (minNumber === maxNumber && Number(number) != Number(minNumber)) {
    return "red";
  }
  if (minNumber != maxNumber && Number(number) < Number(minNumber)) {
    return "red";
  }
  if (minNumber != maxNumber && Number(number) > Number(maxNumber)) {
    return "red";
  }
  return "";
}
// 可以不填写，但如果填写的话，必须是整数数字
export function validateNumberCanNot1(
  rule: any,
  value: any,
  callback: (a?: any) => {}
) {
  const value1 = value.toString();
  if (value1 === "" || value1 === null) {
    callback();
  } else {
    if (isNaN(parseFloat(value1)) && isFinite(value1)) {
      callback(new Error("请输入数字"));
    } else if (!/^[+-]?\d*(\.\d*)?(e[+-]?\d+)?$/.test(value1)) {
      callback(new Error("请输入数字"));
    } else if (value1.indexOf(".") !== -1) {
      callback(new Error("不能为小数"));
    } else if (Number(value1) == 0) {
      callback(new Error("数字不能等于0"));
    } else if (Number(value1) <= 0) {
      callback(new Error("数字不能小于0"));
    } else {
      callback();
    }
  }
}
